package cn.caidabao.camunda_demo.listener.task.create;

import cn.caidabao.camunda_demo.common.CaiCamundaConstant;
import cn.caidabao.camunda_demo.pojo.po.TCaiProcessTask;
import cn.caidabao.camunda_demo.service.ITCaiProcessService;
import cn.caidabao.camunda_demo.service.ITCaiProcessTaskService;
import cn.caidabao.camunda_demo.util.CamundaUtil;
import com.alibaba.fastjson2.JSON;
import lombok.AllArgsConstructor;
import org.camunda.bpm.engine.delegate.DelegateTask;
import org.camunda.bpm.engine.delegate.TaskListener;
import org.camunda.bpm.model.bpmn.instance.ExtensionElements;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author cjn
 * @since 2024-07-16 14:36
 */
@Component
@AllArgsConstructor
public class CaiTaskListener implements TaskListener {

    private final ITCaiProcessTaskService caiProcessTaskService;
    private final ITCaiProcessService caiProcessService;
    private final CamundaUtil camundaUtil;

    @Override
    public void notify(DelegateTask delegateTask) {
        ExtensionElements extensionElements = delegateTask.getBpmnModelElementInstance().getExtensionElements();
        Map<String, String> extensionProperties = camundaUtil.getExtensionProperties(extensionElements);
        TCaiProcessTask processTask = new TCaiProcessTask();
        processTask.setCamundaTaskId(delegateTask.getId());
        processTask.setCaiProcessId(caiProcessService.getByCamundaProcessInstanceId(delegateTask.getProcessInstanceId()).getProcessId());
        processTask.setCaiFormTag(extensionProperties.get(CaiCamundaConstant.processFormTag));
        processTask.setCaiFormType(Integer.parseInt(extensionProperties.get(CaiCamundaConstant.processFormType)));
        processTask.setTaskType(extensionProperties.get(CaiCamundaConstant.processTaskType));
        processTask.setStatus(1);
        processTask.setContent(JSON.toJSONString(delegateTask.getVariables()));
        caiProcessTaskService.save(processTask);
    }
}
